# -*- coding: utf-8 -*-
# @Time : 2022/3/21 9:55
# @Author : Administrator
# @Email : simple_days@qq.com
# @File : MongoUtil.py
# @Project : flaskProject
# ©Copyright : 中国电建集团透平科技有限公司版权所有
from bson import ObjectId
from loguru import logger
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure


class MongoUtil(object):
    URI_CLIENT_DICT = {}  # a dictionary hold all client with uri as key

    def __init__(self, uri,db_name,coll_name):
        self.uri = uri
        self.client = self.new_mongo_client()
        self.database = self.client[db_name]
        self.collection = self.database[coll_name]


    def new_mongo_client(self, **kwargs):
        """Create new pymongo.mongo_client.MongoClient instance. DO NOT USE IT DIRECTLY."""
        try:
            client = MongoClient(self.uri, maxPoolSize=1024, )
            client.admin.command('ismaster')  # The ismaster command is cheap and does not require auth.
        except ConnectionFailure:
            logger.error("new_mongo_client(): Server not available, Please check you uri: {}".format(self.uri))
            return None
        else:
            logger.info(f"get mongodb connection client from {self.uri}")
            return client

    # @property
    # def db(self):
    #     return self.database
    #
    # @property
    # def collection(self):
    #     return self.collection


def objectIDtoStr(document):
    """
    单个文档Bjson objectID转换为字符串
    :param document:
    :return:
    """
    if document is None:
        return None
    document['_id'] = str(document['_id'])
    return document


def strToObjectID(strID: str):
    """
    搜索mongo数据库使用ObjectID
    示例：{'_id': strToObjectID(id)}
    :param strID:
    :return: type-->bson.objectid.ObjectId
    """
    return ObjectId(strID)


if __name__ == '__main__':
    print(type(strToObjectID("61dfd99d5b7bb6e4aa67226d")))
